﻿using System;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;


public class TimeManager : MonoBehaviour
{
    public static TimeManager Instance;
    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;

        }
        Instance = this;
        //DontDestroyOnLoad(gameObject);
    }
  
    [SerializeField] private float _totalTime;
    private float _timeleft;

    public Action<float> OnTimerChanged;
    public float TimeLeft 
    {
        get => _timeleft;
        set 
        {
            if (_timeleft != value) 
            {
                OnTimerChanged?.Invoke(value);
            }
            _timeleft = value;
        }
    }

    private WaitForSeconds _waitTimer;

    

    private void Start()
    {
        _waitTimer = new WaitForSeconds(1);
    }

    public void ResetTime()
    {
        StopAllCoroutines();
        _timeleft = _totalTime;
    }

    public void StartTime()
    {
        ResetTime();
        StartCoroutine(StartTimeCore());
    }
    public void PauseTime()
    {
        
    }

    private IEnumerator StartTimeCore()
    {
        while (true) 
        {
            if(TimeLeft <= 0) 
            {
                //GameSystem.Instance.ChangeGameState(State.Failure);
                
                yield break;
            }else if (TimeLeft == 100) 
            {
                AudioManager.Instance.SetPitch(1.2f);
            }

            yield return _waitTimer;
            TimeLeft--;
        }
    }

    
}
